package com.youwatch.concurrency.example.singleton;

import com.youwatch.concurrency.annotations.Recommend;
import com.youwatch.concurrency.annotations.ThreadSafe;

/**
 * @Author: kss
 * @Description: 单例-懒汉模式-》双重同步锁单例模式
 * 单例实例在第一次使用时进行创建
 * @Date: Create in 2019/1/17
 */
@ThreadSafe
@Recommend
public class SingletonLazybonesSafeRecommend {

    // 构造方法私有化
    private SingletonLazybonesSafeRecommend() {
        // 很多运算操作...初始化多次可能会出错
    }

    // 1、memory = allocate() 分配对象的内存空间
    // 2、cotrInstance() 初始化对象
    // 3、instance = memory 设置instance指向刚分配的内存

    // 单例对象
    private static volatile SingletonLazybonesSafeRecommend instance = null;

    // 静态工厂方法 volatile + 双重检测机制 —> 禁止指令重排
    public static SingletonLazybonesSafeRecommend getInstance() {
        if (instance == null) { // 双重检测机制
            synchronized (SingletonLazybonesSafeRecommend.class) { // 同步锁
                if (instance == null) {
                    instance = new SingletonLazybonesSafeRecommend();
                }
            }
        }
        return instance;
    }

}
